package com.qingzhuge.member.interceptor;

import com.qingzhuge.common.HttpCode;
import com.qingzhuge.controller.base.AbstractController;
import com.qingzhuge.member.dto.CheckAuthorizationRequest;
import com.qingzhuge.member.dto.CheckAuthorizationResponse;
import com.qingzhuge.member.service.ISysMemberService;
import com.qingzhuge.web.interceptor.BaseInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.qingzhuge.common.Constants.CURRENT_USER_ID;

/**
 * @author : zero.xiao
 * @description : 設置用戶id
 * @date :2019-04-04 16:27
 * @modified :
 */
@Component
public class UserInterceptor extends BaseInterceptor {
    @Resource
    private ISysMemberService memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            String headerToken = qingTingProperties.getSecurity().getToken();
            //从header中获取token
            String token = request.getHeader(headerToken);
            //token为空
            if (StringUtils.isNotEmpty(token)) {
                CheckAuthorizationRequest checkAuthRequest = new CheckAuthorizationRequest();
                checkAuthRequest.setToken(token);
                CheckAuthorizationResponse checkAuthResponse = memberService.validToken(checkAuthRequest);
                if (HttpCode.OK.value().equals(checkAuthResponse.getResCode())) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    Object bean = handlerMethod.getBean();
                    if (bean instanceof AbstractController) {
                        AbstractController baseController = (AbstractController) bean;
                        baseController.setUid(checkAuthResponse.getUid());
                    }
                    //设置userId到request里，后续根据userId，获取用户信息
                    request.setAttribute(CURRENT_USER_ID, checkAuthResponse.getUid());
                }
            }
        }
        return true;
    }
}
